package com.mxpio.erp.technology.controller;


import com.mxpio.erp.common.enums.CommonEnums;
import com.mxpio.erp.common.enums.OrderStatusEnums;
import com.mxpio.erp.common.technology.entity.ProcessInfo;
import com.mxpio.erp.common.technology.entity.ProdTecRoutAudit;
import com.mxpio.erp.common.technology.entity.ProdTecRoutProcTmp;
import com.mxpio.erp.common.technology.entity.ProdTecRoutTmp;
import com.mxpio.erp.common.technology.service.*;
import com.mxpioframework.common.vo.Result;
import com.mxpioframework.jpa.policy.CrudContext;
import com.mxpioframework.jpa.policy.impl.SmartCrudPolicyAdapter;
import com.mxpioframework.jpa.query.Criteria;
import com.mxpioframework.jpa.query.Operator;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;


@Tag(name = "ProdTecRoutTmpController", description = "产品工艺路线草稿接口")
@RestController
@RequestMapping("/erp/tech/prodrout/tmp/")
public class ProdTecRoutTmpController {

    @Autowired
    private ProdTecRoutTmpService tmpService;

    @Autowired
    private ProdTecRoutProcTmpService lineTmpService;

    @Autowired
    private ProdTecRoutAuditService auditService;

    @Autowired
    private ProcessInfoService processInfoService;

    @GetMapping("listByItem/{productItemCode}")//点击变更按钮时，请求接口
    @Operation(summary = "产品工艺路线草稿列表", description = "获取产品工艺路线草稿列表（无分页）", method = "GET")
    public Result<ProdTecRoutTmp> listByItem(@Parameter(description="产品物料编号") @PathVariable(name = "productItemCode", required = true) String productItemCode){
        ProdTecRoutTmp routTmp = tmpService.listRoutTmp(productItemCode);
        return Result.OK(routTmp);
    }

    /*@GetMapping("list")//前端未调用接口，暂时注释
    @Operation(summary = "Bom列表", description = "获取Bom列表（无分页）", method = "GET")
    public Result<List<ProdTecRoutTmp>> list(Criteria criteria) throws UnsupportedEncodingException {
        List<ProdTecRoutTmp> bomInfos = tmpService.list(ProdTecRoutTmp.class,criteria);
        return Result.OK(bomInfos);
    }*/


    /*@GetMapping("list/{bomId}")
    @Operation(summary = "根据BomId获取Bom", description = "根据bomId获取Bom", method = "GET")
    public Result<ProdTecRoutTmp> getById(@PathVariable(name = "bomId", required = true) String bomId) {
        ProdTecRoutTmp bomInfo = tmpService.getById(ProdTecRoutTmp.class, bomId);
        return Result.OK(bomInfo);
    }*/

    @RequestMapping("save")
    @Operation(summary = "保存产品工艺路线草稿", description = "保存产品工艺路线草稿")
    public Result<ProdTecRoutTmp> save(@RequestBody ProdTecRoutTmp routTmp) {

        if(StringUtils.isNotBlank(routTmp.getRoutId())){
            ProdTecRoutAudit audit = auditService.getById(ProdTecRoutAudit.class,routTmp.getRoutId());
            if(audit!=null){
                return Result.error("已提交审核");
            }
        }

        if(!tmpService.validBeginTime(routTmp)){
            return Result.error("生效日期必须大于当前最新版本的生效日期");
        }
        List<ProdTecRoutProcTmp> lineList = routTmp.getLineList();
        String processCheckErrorMsg = "";
        for (ProdTecRoutProcTmp line : lineList){
            if (StringUtils.isNotBlank(line.getSchemeCode())){
                Criteria criteria = Criteria.create();
                criteria.addCriterion("processCode", Operator.EQ,line.getProcessCode())
                        .addCriterion("finishCheckFlag", Operator.EQ, CommonEnums.YesNo.YES.getCode());
                List<ProcessInfo> processInfos = processInfoService.list(ProcessInfo.class, criteria);
                if (processInfos.isEmpty()){
                    processCheckErrorMsg +="工序【"+line.getProcessOrder()+":"+line.getProcessCode()+"】非完工检，不需要设置检验方案，请修改；";
                }
            }
        }
        if (StringUtils.isNotBlank(processCheckErrorMsg)){
            return Result.error(processCheckErrorMsg);
        }
        tmpService.save(routTmp,new SmartCrudPolicyAdapter(){
            @Override
            public boolean beforeInsert(CrudContext context) {
                Object o = context.getEntity();
                if(o instanceof ProdTecRoutProcTmp){
                    ((ProdTecRoutProcTmp) o).setRoutId(routTmp.getRoutId());
                }
                return true;
            }
        });
        return Result.OK(routTmp);
    }

    @RequestMapping("saveAndSubmit")
    @Operation(summary = "保存并提交产品工艺路线草稿", description = "保存并提交产品工艺路线草稿")
    public Result<ProdTecRoutTmp> saveAndSubmit(@RequestBody ProdTecRoutTmp routTmp) {

        if(!tmpService.validBeginTime(routTmp)){
            return Result.error("生效日期必须大于当前最新版本的生效日期");
        }

        if(StringUtils.isNotBlank(routTmp.getRoutId())){
            ProdTecRoutTmp bomInfoTmp = tmpService.getById(ProdTecRoutTmp.class,routTmp.getRoutId());
            if(bomInfoTmp!=null && !OrderStatusEnums.BomStatus.CREATE.getStatusCode().equals(bomInfoTmp.getUseType())
                    && !OrderStatusEnums.BomStatus.AUDITING.getStatusCode().equals(bomInfoTmp.getUseType())){
                return Result.error("已提交审核");
            }

            ProdTecRoutAudit audit = auditService.getById(ProdTecRoutAudit.class,routTmp.getRoutId());
            if(audit!=null){
                return Result.error("已提交审核");
            }

        }
        List<ProdTecRoutProcTmp> lineList = routTmp.getLineList();
        String processCheckErrorMsg = "";
        for (ProdTecRoutProcTmp line : lineList){
            if (StringUtils.isNotBlank(line.getSchemeCode())){
                Criteria criteria = Criteria.create();
                criteria.addCriterion("processCode", Operator.EQ,line.getProcessCode())
                        .addCriterion("finishCheckFlag", Operator.EQ, CommonEnums.YesNo.YES.getCode());
                List<ProcessInfo> processInfos = processInfoService.list(ProcessInfo.class, criteria);
                if (processInfos.isEmpty()){
                    processCheckErrorMsg +="工序【"+line.getProcessOrder()+":"+line.getProcessCode()+"】非完工检，不需要设置检验方案，请修改；";
                }
            }
        }
        if (StringUtils.isNotBlank(processCheckErrorMsg)){
            return Result.error(processCheckErrorMsg);
        }
        tmpService.save(routTmp,new SmartCrudPolicyAdapter(){
            @Override
            public boolean beforeInsert(CrudContext context) {
                Object o = context.getEntity();
                if(o instanceof ProdTecRoutProcTmp){
                    ((ProdTecRoutProcTmp) o).setRoutId(routTmp.getRoutId());
                }
                return true;
            }
        });
        if(tmpService.audit(routTmp.getRoutId())){
            return Result.OK(routTmp);
        }
        return Result.error("提交出错");
    }

    /*@DeleteMapping("remove/{bomIds}")
    @Operation(summary = "根据bomId删除Bom", description = "删除Bom", method = "DELETE")
    @Transactional(readOnly = false)
    public Result<ProdTecRoutTmp> remove(@Parameter(description="bomId，多个单号用英文逗号分隔") @PathVariable(name = "bomIds", required = true) String bomIds) {
        String[] bomId = bomIds.split(",");
        for(String key : bomId){
            Criteria c = Criteria.create().addCriterion("bomId", Operator.EQ, key);
            bomInfoLineTmpService.removeBatch(BomInfoLineTmp.class, c);
            tmpService.delete(ProdTecRoutTmp.class, key);
        }
        return Result.OK();
    }

    @PutMapping("submit/{bomId}")
    @Operation(summary = "提交Bom", description = "提交Bom", method = "PUT")
    public Result<ProdTecRoutTmp> submit(@Parameter(description="bomId") @PathVariable(name = "bomId", required = true) String bomId) {
        ProdTecRoutTmp bomInfo = tmpService.getById(ProdTecRoutTmp.class,bomId);
        if(bomInfo.getUseType().equals(OrderStatusEnums.BomStatus.CREATE.getStatusCode())){
            return tmpService.updateBomStatus(bomInfo, OrderStatusEnums.BomStatus.AUDITING);
        }else {
            return Result.error("非新增状态不可提交");
        }
    }

    @PutMapping("audit/{bomId}")
    @Operation(summary = "审核Bom", description = "审核Bom", method = "PUT")
    public Result<ProdTecRoutTmp> audit(@Parameter(description="bomId") @PathVariable(name = "bomId", required = true) String bomId) {
        ProdTecRoutTmp bomInfo = tmpService.getById(ProdTecRoutTmp.class,bomId);
        if(bomInfo.getUseType().equals(OrderStatusEnums.BomStatus.CREATE.getStatusCode())){
            return tmpService.updateBomStatus(bomInfo, OrderStatusEnums.BomStatus.USING);
        }else {
            return Result.error("非审核中状态不可审核");
        }
    }

    @PutMapping("abandon/{bomId}")
    @Operation(summary = "弃审Bom", description = "弃审Bom", method = "PUT")
    public Result<ProdTecRoutTmp> abandon(@Parameter(description="bomId") @PathVariable(name = "bomId", required = true) String bomId) {
        ProdTecRoutTmp bomInfo = tmpService.getById(ProdTecRoutTmp.class,bomId);
        if(bomInfo.getUseType().equals(OrderStatusEnums.BomStatus.AUDITING.getStatusCode())){
            return tmpService.updateBomStatus(bomInfo, OrderStatusEnums.BomStatus.CREATE);
        }else{
            return Result.error("非审核中状态不可审核");
        }
    }

    @PutMapping("expired/{bomId}")
    @Operation(summary = "失效Bom", description = "失效Bom", method = "PUT")
    public Result<ProdTecRoutTmp> expired(@Parameter(description="bomId") @PathVariable(name = "bomId", required = true) String bomId) {
        ProdTecRoutTmp bomInfo = tmpService.getById(ProdTecRoutTmp.class,bomId);
        return tmpService.updateBomStatus(bomInfo, OrderStatusEnums.BomStatus.EXPIRED);
    }
    @PutMapping("voided/{bomId}")
    @Operation(summary = "作废Bom", description = "作废Bom", method = "PUT")
    public Result<ProdTecRoutTmp> voided(@Parameter(description="bomId") @PathVariable(name = "bomId", required = true) String bomId) {
        ProdTecRoutTmp bomInfo = tmpService.getById(ProdTecRoutTmp.class,bomId);
        return tmpService.updateBomStatus(bomInfo, OrderStatusEnums.BomStatus.CREATE);
    }

    @PutMapping("toAudit/{bomId}")
    @Operation(summary = "提交Bom至审批功能", description = "提交Bom至审批功能", method = "PUT")
    public Result<ProdTecRoutTmp> toAudit(@Parameter(description="bomId") @PathVariable(name = "bomId", required = true) String bomId) {
        ProdTecRoutTmp bomInfoTmp = tmpService.getById(ProdTecRoutTmp.class,bomId);
        if(!OrderStatusEnums.BomStatus.CREATE.getStatusCode().equals(bomInfoTmp.getUseType())){
            return Result.error("已提交审核");
        }

        ProdTecRoutAudit audit = bomInfoAuditService.getById(ProdTecRoutAudit.class,bomId);
        if(audit!=null){
            return Result.error("已提交审核");
        }

        if(tmpService.audit(bomId)){
            return Result.OK();
        }
        return Result.error("提交出错");
    }*/

}
